package core

import (
	"log"
	"net"
)

type Dev struct {
	DevID      string `json:"devId"`
	IP         string `json:"ip"`
	Port       int    `json:"port"`
	Mode       int    `json:"mode"`
	VoicePower int    `json:"voicePower"`

	Ts               int64 `json:"ts"`
	Locked           bool  `json:"locked"`
	LockedByLevel    int   `json:"lockedByLevel"`
	LockedByUserID   int   `json:"lockedByUserId"`
	SpeechPacketTime int64 `json:"speechPacketTime"`

	CurrentTask *Task `json:"-"`

	Addr *net.UDPAddr `json:"-"`
}

type DevStatusMsg struct {
	MsgType        int    `json:"msgType"`
	DevID          string `json:"deviceId"`
	IP             string `json:"deviceIp"`
	OnSpeech       bool   `json:"onSpeech"`
	OnPlaying      bool   `json:"onPlaying"`
	Online         bool   `json:"online"`
	Mode           int    `json:"mode"`
	LockedByUserID int    `json:"lockedByUserId"`
	Time           int64  `json:"time"`
}

func (d *Dev) Send(b []byte) {
	s := GetUDPServer()
	if ctx.Conf.TestMode {
		log.Println(len(b))
	}
	s.Send(b, d.Addr)
}

func (d *Dev) Heartbeat() {
	b := []byte{0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb}
	s := GetUDPServer()
	s.Send(b, d.Addr)
}

func (d *Dev) OpenSound() {
	b := make([]byte, 45)
	b[0] = 0xaf
	b[1] = byte(45)
	b[2] = 0x00
	b[3] = 0x00
	b[4] = 0x00

	b[5] = 0x00
	b[6] = 0x00
	b[7] = 0x00
	b[8] = 0x00

	b[9] = 0x01
	b[10] = 0x01
	b[11] = 0x03

	b[12] = 0x00
	b[13] = 0x00

	b[14] = 0x01
	b[15] = 0x00

	// append port
	pb := IntToBytes(d.Port)
	b[16] = pb[0]
	b[17] = pb[1]
	b[18] = pb[2]
	b[19] = pb[3]

	// append device id
	ib := []byte(d.DevID)
	for i := 0; i < len(ib); i++ {
		b[20+i] = ib[i]
	}

	// append check word
	cw := 0
	for i := 0; i < len(b)-1; i++ {
		cw += int(b[i] & 0xff)
	}
	cw = 256 - cw
	b[44] = byte(cw)

	s := GetUDPServer()
	s.Send(b, d.Addr)
}

func (d *Dev) ChangeMode() {
	b := make([]byte, 45)
	b[0] = 0xaf
	b[1] = byte(45)
	b[2] = 0x00
	b[3] = 0x00
	b[4] = 0x00

	b[5] = 0x00
	b[6] = 0x00
	b[7] = 0x00
	b[8] = 0x00

	b[9] = 0x01
	b[10] = 0x01
	b[11] = 0x01

	b[12] = 0x00
	b[13] = 0x00

	b[14] = 0x03
	b[15] = 0x00

	// append port
	pb := IntToBytes(d.Port)
	b[16] = pb[0]
	b[17] = pb[1]
	b[18] = pb[2]
	b[19] = pb[3]

	// append device id
	ib := []byte(d.DevID)
	for i := 0; i < len(ib); i++ {
		b[20+i] = ib[i]
	}

	// append check word
	cw := 0
	for i := 0; i < len(b)-1; i++ {
		cw += int(b[i] & 0xff)
	}
	cw = 256 - cw
	b[44] = byte(cw)

	s := GetUDPServer()
	s.Send(b, d.Addr)
}
